package com.pagoda.nerp.trade.app.account.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.pagoda.nerp.trade.common.BaseResult;
import com.pagoda.nerp.trade.common.ConstantDefine;
import com.pagoda.nerp.trade.common.enums.ErrorCodeMappingEnums;
import com.pagoda.nerp.trade.entity.PurGoodsRequest;
import com.pagoda.nerp.trade.entity.PurVendorListprice;
import com.pagoda.nerp.trade.service.PurGoodsRequestService;
import com.pagoda.nerp.trade.service.PurVendorListpriceService;
import com.pagoda.nerp.trade.service.SysConfigureService;

@Controller
@RequestMapping(value = "/purchase")
public class PurchaseMgrController {
	
	private static final Logger logger = Logger.getLogger(PurchaseMgrController.class);
	
	@Autowired
	private PurGoodsRequestService purGoodsRequestService;
	
	@Autowired
	private SysConfigureService sysConfigureService;
	
	@Autowired
	private PurVendorListpriceService purVendorListpriceService;
	
	/**
	 * 添加采购需求计划
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/addGoodsRequest", method = RequestMethod.POST)
	@ResponseBody
	public BaseResult<Object> addGoodsRequest(@RequestBody Map requestMap) {
		try {
			List<Map<String, Object>> requests = (List<Map<String, Object>>)requestMap.get("requests");
			if (null == requests||requests.size()<=0) {
				return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
			}

			SimpleDateFormat df=new SimpleDateFormat(ConstantDefine.DATE_FORMAT);
			List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
			for (int i = 0; i < requests.size(); i++) {
				PurGoodsRequest request=new PurGoodsRequest();
				Map<String, Object> map = requests.get(i);
				String interGoodsRequestCode = map.get("interGoodsRequestCode") == null ? "" : map.get("interGoodsRequestCode").toString();
				Map<String, Object> data = new HashMap<String, Object>();
				data.put("interGoodsRequestCode", interGoodsRequestCode);
				try {
					// 校验参数合法性
					if (null == map.get("interGoodsRequestCode")
							|| null == map.get("warehouseOrgName")
							|| null == map.get("warehouseOrgCode")
							|| null == map.get("expectStartDate")
							|| null == map.get("expectEndDate")
							|| null == map.get("goodsCategory")
							|| null == map.get("goodsCode")
							|| null == map.get("goodsName")
							|| null == map.get("goodSpec")
							|| null == map.get("goodsStandardCode")
							|| null == map.get("purUnitName")
							|| null == map.get("buyPrice")
							|| null == map.get("requestQty")
							|| null == map.get("publishType")
							|| null == map.get("begPubDate")
							|| null == map.get("lastPubDate")
							|| null == map.get("lastReviewDate")
							|| null == map.get("quotaCond")
							|| null == map.get("minOrderQty")
							|| null == map.get("selectVendorType")
							|| null == map.get("vendorList")
							|| null == map.get("remark")) {
						data.put("errorCode", ErrorCodeMappingEnums.ERROR_INVALID_PARAMS.getErrorCode());
						data.put("errorMsg", ErrorCodeMappingEnums.ERROR_INVALID_PARAMS.getErrorMsg());
						resultList.add(data);
						continue;
					}
					request.setCategoryCode(map.get("goodsCategory").toString());
					request.setGoodsCode(map.get("goodsCode").toString());
					request.setGoodsName(map.get("goodsName").toString());
					request.setItemSpec(map.get("goodSpec").toString());
					request.setPurUnitName(map.get("purUnitName").toString());
					request.setGoodsRequestOrgCode(map.get("warehouseOrgCode").toString());
					request.setExpectStartDate(df.parse(map.get("expectStartDate").toString()));
					request.setExpectEndDate(df.parse(map.get("expectEndDate").toString()));
					request.setPublishType(map.get("publishType").toString());
					request.setPubTime(df.parse(map.get("begPubDate").toString()));
					request.setRemark(map.get("remark").toString());
					request.setLastReviewDate(df.parse(map.get("lastReviewDate").toString()));
					request.setLastPubDate(df.parse(map.get("lastPubDate").toString()));
					request.setVendorList(map.get("vendorList").toString());
					request.setBuyPrice(Long.parseLong(map.get("buyPrice").toString()));
					request.setRequestQty(Long.parseLong(map.get("requestQty").toString()));
					request.setMinOrderQty(Long.parseLong(map.get("minOrderQty").toString()));
					request.setSelectVendorType(map.get("selectVendorType").toString());
					request.setGoodsRequestName(map.get("requirementDesc").toString());
					request.setGoodsStandardCode(map.get("goodsStandardCode").toString());
					
					String goodsRequestCode = purGoodsRequestService.insert(request);
					data.put("pltRequestCode", goodsRequestCode);
					
				} catch (Exception e) {
					logger.error("add purGoodsRequest failed with interGoodsRequestCode="+interGoodsRequestCode, e);
					data.put("errorCode", ErrorCodeMappingEnums.ERROR_EXCEPTION_DB_DML.getErrorCode());
					data.put("errorMsg", ErrorCodeMappingEnums.ERROR_EXCEPTION_DB_DML.getErrorMsg());
				}
				
				resultList.add(data);
			}
			
			return new BaseResult<Object>(ErrorCodeMappingEnums.SUCCESS, resultList);
			
		} catch (Exception e) {
			logger.error("add purGoodsRequest failed", e);
			return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR);
		}

	}
	
	
	/**
	 * 查询采购计划列表
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/queryGoodsRequestList", method = RequestMethod.POST)
	@ResponseBody
	public BaseResult<Object> queryGoodsRequestList(@RequestBody Map map) {
		try {
			// 校验参数合法性
			if (null == map.get("goodsRequestOrgCode")
					||null == map.get("goodsCategory")
					||null == map.get("pageNo")
					||null == map.get("pageSize")) {
				return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
			}
			
			//分页设置
			int pageNo = map.get("pageNo") == null ? 1 : Integer.parseInt(map.get("pageNo").toString());
			int pageSize = map.get("pageSize") == null ? 10 : Integer.parseInt(map.get("pageSize").toString());
			PageHelper.startPage(pageNo, pageSize, false);//开始分页,不统计总数

			List<PurGoodsRequest> requestList = purGoodsRequestService.selectAllByConditon(map);
			return new BaseResult<Object>(ErrorCodeMappingEnums.SUCCESS, requestList);
		} catch (Exception e) {
			logger.error("query purGoodsRequest  failed", e);
			return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR);
		}

	}
	
	/**
	 * 首页广播采购计划
	 * 
	 * @return
	 */
	@RequestMapping(value = "/queryGoodsRequestLatest", method = RequestMethod.POST)
	@ResponseBody
	public BaseResult<Object> queryGoodsRequestLatest() {
		try {
			List<PurGoodsRequest> requestList = purGoodsRequestService.selectLatest();
			return new BaseResult<Object>(ErrorCodeMappingEnums.SUCCESS, requestList);
		} catch (Exception e) {
			logger.error("query latest purGoodsRequest for index page  failed", e);
			return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR);
		}

	}
	
	/**
	 * 查询采购计划详情
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/queryGoodsRequestDetail", method = RequestMethod.POST)
	@ResponseBody
	public BaseResult<Object> queryGoodsRequestDetail(@RequestBody Map map) {
		try {
			// 校验参数合法性
			if (null == map.get("goodsRequestId")) {
				return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
			}
			
			PurGoodsRequest goodsRequest = purGoodsRequestService.selectOneByCondition(map);
			if (goodsRequest==null) {
				return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR_INVALID_DB_RECORD);
			}
			return new BaseResult<Object>(ErrorCodeMappingEnums.SUCCESS, goodsRequest);
		} catch (Exception e) {
			logger.error("query purGoodsRequestDetail  failed", e);
			return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR);
		}

	}

	/**
	 * 通过商品标准id获取商品质检标准页面url
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/generateUrl", method = RequestMethod.POST)
	@ResponseBody
	public BaseResult<Object> generateUrl(@RequestBody Map map) {
		try {
			// 校验参数合法性
			if (null == map.get("goodsStandardCode")) {
				return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
			}
			String goodsStandardUrl = sysConfigureService.selectByCondition(ConstantDefine.SYS_CONFIG_GOODS_STANDARD_URL);
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("goodsStandardUrl", goodsStandardUrl+"?goodsStandardCode="+map.get("goodsStandardCode").toString());
			return new BaseResult<Object>(ErrorCodeMappingEnums.SUCCESS, data);
		} catch (Exception e) {
			logger.error("query purGoodsRequest  failed", e);
			return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR);
		}

	}
	
	/**
	 * 添加报价
	 * 
	 * @param listPrice
	 * @return
	 */
	@RequestMapping(value = "/addListPrice", method = RequestMethod.POST)
	@ResponseBody
	public BaseResult<Object> addListPrice(@RequestBody PurVendorListprice listPrice) {
		try {
			// 校验参数合法性
			if (StringUtils.isEmpty(listPrice.getVendorCode())
					|| StringUtils.isEmpty(listPrice.getGoodsCode())
					|| StringUtils.isEmpty(listPrice.getGoodsName())
					|| StringUtils.isEmpty(listPrice.getGoodsPacking())
					|| StringUtils.isEmpty(listPrice.getSettleType())
					|| StringUtils.isEmpty(listPrice.getSendAddr())
					|| StringUtils.isEmpty(listPrice.getGoodsSpec())
					|| StringUtils.isEmpty(listPrice.getSupplyArea())
					|| StringUtils.isEmpty(listPrice.getPhoneNumber())) {
				return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
			}
			
			int resultCode = purVendorListpriceService.insert(listPrice);
			if (resultCode<0) {
				return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR_EXCEPTION_DB_DML);
			}
			
			return new BaseResult<Object>(ErrorCodeMappingEnums.SUCCESS);
		} catch (Exception e) {
			logger.error("add listPrice  failed", e);
			return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR);
		}

	}
	
	
	/**
	 * 查询报价单列表
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/queryListPrice", method = RequestMethod.POST)
	@ResponseBody
	public BaseResult<Object> queryListPrice(@RequestBody Map map) {
		try {
			// 校验参数合法性
			if (null == map.get("vendorId") 
					|| null == map.get("pageNo")
					|| null == map.get("pageSize")) {
				return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
			}

			//分页设置
			int pageNo = map.get("pageNo") == null ? 1 : Integer.parseInt(map.get("pageNo").toString());
			int pageSize = map.get("pageSize") == null ? 10 : Integer.parseInt(map.get("pageSize").toString());
			PageHelper.startPage(pageNo, pageSize, false);//开始分页,不统计总数

			List<PurVendorListprice> list = purVendorListpriceService.selectListByContifion(Integer.parseInt(map.get("vendorId").toString()));
			return new BaseResult<Object>(ErrorCodeMappingEnums.SUCCESS, list);
		} catch (Exception e) {
			logger.error("query listPrice list failed", e);
			return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR);
		}

	}
	
	
	/**
	 * 查询报价单列表(提供给供应商平台，通过采购单获取报价列表)
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/queryListPriceByRequest", method = RequestMethod.POST)
	@ResponseBody
	public BaseResult<Object> queryListPriceByRequest(@RequestBody Map map) {
		try {
			// 校验参数合法性
			if (null == map.get("pltRequestCode")) {
				return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
			}
			
			List<Map<String, Object>> data = purVendorListpriceService.selectListByRequest(map.get("pltRequestCode").toString());
			return new BaseResult<Object>(ErrorCodeMappingEnums.SUCCESS, data);
		} catch (Exception e) {
			logger.error("query listPrice list failed", e);
			return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR);
		}

	}
	
	/**
	 * 查询报价单详情
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/queryListPriceDetail", method = RequestMethod.POST)
	@ResponseBody
	public BaseResult<Object> queryListPriceDetail(@RequestBody Map map) {
		try {
			// 校验参数合法性
			if (null == map.get("vendorListPriceId")) {
				return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
			}
			
			PurVendorListprice listPrice = purVendorListpriceService.selectOneByContifion(Integer.parseInt(map.get("vendorListPriceId").toString()));
			return new BaseResult<Object>(ErrorCodeMappingEnums.SUCCESS, listPrice);
		} catch (Exception e) {
			logger.error("query listPrice detail failed", e);
			return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR);
		}
	}
	
	/**
	 * 撤销报价
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/cancleListPrice", method = RequestMethod.POST)
	@ResponseBody
	public BaseResult<Object> cancleListPrice(@RequestBody Map map) {
		try {
			// 校验参数合法性
			if (null == map.get("vendorListPriceId")) {
				return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
			}
			map.put("listpriceStatus", "C");
			purVendorListpriceService.updateStatus(map);
			return new BaseResult<Object>(ErrorCodeMappingEnums.SUCCESS);
		} catch (Exception e) {
			logger.error("query listPrice detail failed", e);
			return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR);
		}
	}
	
	/**
	 * 撤销采购需求单
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/cancleGoodsRequest", method = RequestMethod.POST)
	@ResponseBody
	public BaseResult<Object> cancleGoodsRequest(@RequestBody Map map) {
		try {
			List<String> list=(List<String>)map.get("codes");
			// 校验参数合法性
			if (null == list||list.size()<=0) {
				return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR_INVALID_PARAMS);
			}
			List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
			for (int i = 0; i < list.size(); i++) {
				int resultCode = purGoodsRequestService.updateStatus(String.valueOf(list.get(i)));
				Map<String, Object> data = new HashMap<String, Object>();
				if (resultCode==1) {
					data.put("result", "ok");
				}else {
					data.put("result", "");
				}
				data.put("pltRequestCode", list.get(i));
				resultList.add(data);
			}
			return new BaseResult<Object>(ErrorCodeMappingEnums.SUCCESS,resultList);
		} catch (Exception e) {
			logger.error("query listPrice detail failed", e);
			return new BaseResult<Object>(ErrorCodeMappingEnums.ERROR);
		}
	}
}
